<template>
  <!--  :model="form"-->
  <el-form ref="form" :model="spuForm" label-width="80px">
    <el-form-item label="SPU名称">
      <el-input placeholder="SPU名称" v-model="spuForm.spuName"></el-input>
    </el-form-item>
    <el-form-item label="品牌">
      <el-select v-model="spuForm.tmId" placeholder="请选择品牌">
        <el-option :label="tm.tmName" :value="tm.id" v-for="(tm,index) in trademarkList" :key="tm.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input type="textarea" v-model="spuForm.description" rows="4"></el-input>
    </el-form-item>
    <el-form-item label="SPU图片">
      <el-upload
        action="/dev-api/admin/product/fileUpload"
        list-type="picture-card"
        :file-list="spuImageList"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt/>
      </el-dialog>
    </el-form-item>
    <el-form-item label="销售属性" :inline="true">
      <el-select v-model="saleAttrIdName"
                 :placeholder="unSelectorSaleAttrList.length>0?`还有${unSelectorSaleAttrList.length}个未选择`:'没有啦'">
        <el-option :label="item.name" :value="`${item.id}:${item.name}`" v-for="(item,index) in unSelectorSaleAttrList"
                   :key="item.id"></el-option>
      </el-select>
      <el-button type="primary" @click="addSaleAttr" :disabled="!saleAttrIdName">添加销售属性</el-button>
      <el-table style="width: 100%" border :data="spuForm.spuSaleAttrList">
        <el-table-column prop="prop" align="center" type="index" label="序号" width="80"></el-table-column>
        <el-table-column prop="saleAttrName" label="属性名" width="width"></el-table-column>
        <el-table-column prop="prop" label="属性名称列表" width="width">
          <template slot-scope="{row,$index}">
            <el-tag
              :key="saleAttrValue.id"
              v-for="(saleAttrValue, index) in row.spuSaleAttrValueList"
              closable
              :disable-transitions="false"
              @close="row.spuSaleAttrValueList.splice($index,1)"
            >
              {{ saleAttrValue.saleAttrValueName }}
            </el-tag>
            <el-input
              class="input-new-tag"
              v-if="row.inputVisible"
              v-model="row.saleAttrValueName"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="toButton(row)"
              @blur="toButton(row)"
            >
            </el-input>
            <el-button v-else class="button-new-tag" size="small" @click="toInput(row)">+添加</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="prop" label="操作" width="width">
          <template slot-scope="{row,$index}">
            <HintButton type="danger" size="mini" icon="el-icon-delete" title="删除"
                        @click="spuForm.spuSaleAttrList.splice($index,1)"></HintButton>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item :inline="true">
      <el-button type="primary" @click="save">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  name: "SpuForm",
  props: ["visible"],
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      spuForm: {
        category3Id: 0,
        spuName: "",
        description: "",
        spuImageList: [
          //{
          // imgName: "string",
          // imgUrl: "string",
          // spuId: 0
          // }
        ],
        spuSaleAttrList: [
          //{
          // baseSaleAttrId: 0,
          // saleAttrName: "",
          // spuId: 0,
          // spuSaleAttrValueList: [
          // {
          //   baseSaleAttrId: 0,
          //   isChecked: "string",
          //   saleAttrName: "",
          //   saleAttrValueName: "string",
          //   spuId: 0
          // }
          //   ]
          // }
        ],
        tmId: 0
      },
      category3Id: "",
      spuImageList: [], //请求初始化的spu图片列表
      trademarkList: [], //请求初始化的所有品牌列表
      baseSaleAttrList: [], //请求初始化的所有的销售属性列表
      saleAttrIdName: "",
      inputVisible: false,//标签
      inputValue: ''
    };
  },
  methods: {
    //图片相关的回调 官方copy过来的
    //图片移除
    handleRemove(file, fileList) {
      //console.log(file, fileList);
      this.spuImageList = fileList
    },
    //图片上传成功
    handleSuccess(response, file, fileList) {
      //console.log(fileList)
      this.spuImageList = fileList
    },
    //点击文件列表中已上传的文件时的钩子
    handlePictureCardPreview(res, file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
      //console.log(res,file)
    },
    async getInitUpdateSpuFormData(row, category3Id) {
      this.spuForm.category3Id = category3Id
      //获取spu的id获取详情
      //http://localhost:9529/dev-api/admin/product/getSpuById/1858
      try {
        const result1 = await this.$API.spu.getSpu(row.id);
        //console.log(result1)
        if (result1.code === 200 || result1.code === 20000) {
          this.spuForm = result1.data;
        }
      } catch (error) {
        this.$message.error("获取spu请求信息失败");
      }

      //根据id获取图片信息
      //http://localhost:9529/dev-api/admin/product/spuImageList/1858
      try {
        const result2 = await this.$API.sku.getSpuImageList(row.id);
        // console.log(result2)
        if (result2.code === 200 || result2.code === 20000) {
          let spuImageList = result2.data;
          spuImageList.forEach(item => {
            item.name = item.imgName
            item.url = item.imgUrl
          })
          this.spuImageList = spuImageList
        }
      } catch (error) {
        this.$message.error("获取图片请求失败");
      }
    },
    async getInitAddSpuFormData(category3Id) {
      this.category3Id=category3Id
      //点击添加按钮的时候 发了2个请求 在spu组件中需要定义这2个请求
      //http://localhost:9529/dev-api/admin/product/baseTrademark/getTrademarkList
      //http://localhost:9529/dev-api/admin/product/baseSale属性AttrList
      //初始化函数,此函数是点击父组件中的添加spu按钮触发的4个请求 在写好的页面找2个
      //获取品牌列表
      //http://localhost:9529/dev-api/admin/product/baseTrademark/getTrademarkList
      try {
        const result3 = await this.$API.trademark.getTrademarkList();
        // console.log(result3)
        this.trademarkList = result3.data;
      } catch (error) {
        this.$message.error("获取品牌请求失败");
      }
      //获取所有属性列表
      //http://localhost:9529/dev-api/admin/product/baseSaleAttrList
      try {
        const result4 = await this.$API.spu.getBaseSaleAttrList();
        //console.log(result4)
        this.baseSaleAttrList = result4.data;
      } catch (error) {
        this.$message.error("获取所有属性列表请求失败");
      }
    },
    //添加销售属性
    addSaleAttr(row) {
      let [baseSaleAttrId, saleAttrName] = this.saleAttrIdName.split(":")
      let obj = {
        saleAttrName,
        baseSaleAttrId,
        spuSaleAttrValueList: []
      }
      this.spuForm.spuSaleAttrList.push(obj)
     this.saleAttrName = ""
    },
    //el-tag相关的 从官网复制过来的
    //点击button标签切换成input框
    toInput(row) {
      //添加saleAttrValueName 和inputVisible 两个响应式的属性
      this.$set(row, 'inputVisible', true)
      this.$set(row, 'saleAttrValueName', "")
      //自动获取焦点
      this.$nextTick(() => {
        this.$refs.saveTagInput.focus()
      });
    },
// 当input框 失去焦点和点击回车时切换成
    toButton(row) {
      let {baseSaleAttrId, saleAttrValueName} = row
      let obj = {baseSaleAttrId, saleAttrValueName}
      if (saleAttrValueName.trim() === "") {
        row.saleAttrValueName = "" //清空输入框
        row.inputVisible = false//切换成button
        return//结束本函数
      }
      //判断是否重复
      let isRepeat = row.spuSaleAttrValueList.some(item => {
        return item.saleAttrValueName === saleAttrValueName
      })
      if (isRepeat) {
        this.$message.success('属性值不能重复')
        row.saleAttrValueName = "" //清空输入框
        return;
      }
      row.spuSaleAttrValueList.push(obj)//添加到数组中
      row.inputVisible = false;//input框关闭
      row.saleAttrValueName = ""//清空输入框
    },
    //点击保存按钮
   async save() {
      //获取参数   //整理参数
      let {spuForm, spuImageList, category3Id} = this
      spuForm.category3Id = category3Id
      spuForm.spuSaleAttrList.forEach(item => {
        delete item.inputVisible
        delete item.saleAttrValueName
      })
      spuForm.spuImageList=spuImageList.map(item => {
        return {
          imgName: item.name,
          imgUrl: item.imgUrl || item.response.data
        }
      })
      //发请求
      try {
        const result = await this.$API.spu.addOrUpdateSpuInfo(spuForm)
        if (result.code===200||result.code===20000){
          console.log(result)
          this.$message.success('添加spu成功')
          this.$emit('update:visible',false)//回到父组件
          this.$emit('backSuccess')//告诉父组件回来了
          this.resetData()//清空data中的数据
        }else {
          this.$message.error('保存spu属性失败')
        }
      } catch (error) {
      this.$message.error('保存spu属性请求失败')
      }

    },
    //点击取消按钮
    cancel(){
      this.$emit('update:visible',false)//返回父组件
      this.$emit('backCancel')//通知父组件 取消标志位
      this.resetData()//清空data中的数据
    },
    //清空data中的数据 为了复用 所以写成一个函数的形式
    resetData(){
      this.dialogImageUrl="",
        this.dialogVisible=false,
        this.spuForm={
        category3Id: 0,
          spuName: "",
          description: "",
          spuImageList: [],
          spuSaleAttrList: [],
          tmId: 0
      },
        this.category3Id= "",
        this.spuImageList=[], //请求初始化的spu图片列表
        this.trademarkList=[], //请求初始化的所有品牌列表
        this.baseSaleAttrList=[], //请求初始化的所有的销售属性列表
        this.saleAttrIdName="",
        this.inputVisible=false,//标签
        this.inputValue=''
    }
  },
  computed: {
    unSelectorSaleAttrList() {
      return this.baseSaleAttrList.filter(item => {
        return this.spuForm.spuSaleAttrList.every(item1 => {
          return item.name !== item1.saleAttrName
        })
      })
    }
  }
};
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
